package cn.flying.base.process.listener.eventlistener;

import javax.annotation.Resource;

import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.ActivitiExceptionEvent;
import org.activiti.engine.delegate.event.impl.ActivitiEntityExceptionEventImpl;
import org.activiti.engine.impl.persistence.entity.JobEntityImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.flying.base.process.listener.handler.JobExecutionFailureListenerHandler;


/**
 * @description: 异常监听器
 * @author: lvyong
 * @date: 2023年02月22日 23:33
 * @version: 1.0
 */
@Component
public class JobExecutionFailureListener implements ActivitiEventListener, ActivitiExceptionEvent {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Throwable throwable;

    @Resource
    private JobExecutionFailureListenerHandler jobExecutionFailureListenerHandler;

    /**
     * Called when an event has been fired
     *
     * @param event the event
     */
    @Override
    public void onEvent(ActivitiEvent event) {
        ActivitiEntityExceptionEventImpl exceptionEvent = (ActivitiEntityExceptionEventImpl) event;
        throwable = exceptionEvent.getCause();
        String executionId = exceptionEvent.getExecutionId();
        JobEntityImpl entity = (JobEntityImpl) exceptionEvent.getEntity();
        ActivitiEventType eventType = exceptionEvent.getType();
        String processDefinitionId = exceptionEvent.getProcessDefinitionId();
        String processInstanceId = exceptionEvent.getProcessInstanceId();

//        CfProcException procException = new CfProcException();
//        procException.setProcInstId(processInstanceId);
//        procException.setExecutionId(executionId);
//        procException.setProcDefId(processDefinitionId);
//        procException.setProcDefKey("");
//        procException.setProcDefName("");
//        procException.setActivitiId("");
//        procException.setActivitiName("");
//        procException.setBizKey("");
//        procException.setExceptionMsg("");
//        procException.setExceptionTrace("");
//        procException.setDealState("");
//        procException.setTenantId("");
//
//        jobExecutionFailureListenerHandler.execute(procException);
    }

    /**
     * @return whether or not the current operation should fail when this listeners execution throws an exception.
     */
    @Override
    public boolean isFailOnException() {
        return false;
    }

    /**
     * @return the throwable that caused this event to be dispatched.
     */
    @Override
    public Throwable getCause() {
        return throwable;
    }
}
